<template>
  <div class="log-manager-container">
    <!-- 工具栏 -->
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <!-- 搜索和过滤 -->
        <div class="search-filters">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索日志..."
            :prefix-icon="Search"
            clearable
            size="small"
            class="search-input"
            @input="handleSearch"
          />
          
          <el-select
            v-model="selectedLevel"
            placeholder="级别"
            clearable
            size="small"
            class="level-select"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="DEBUG" value="DEBUG" />
            <el-option label="INFO" value="INFO" />
            <el-option label="WARN" value="WARN" />
            <el-option label="ERROR" value="ERROR" />
          </el-select>
          
          <el-select
            v-model="selectedCategory"
            placeholder="分类"
            clearable
            size="small"
            class="category-select"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="系统" value="system" />
            <el-option label="音频" value="audio" />
            <el-option label="用户" value="user" />
            <el-option label="网络" value="network" />
            <el-option label="文件" value="file" />
          </el-select>
          
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="small"
            class="date-picker"
            @change="handleFilter"
          />
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
            type="primary"
            :icon="Refresh"
            size="small"
            @click="refreshLogs"
            :loading="isRefreshing"
          >
            刷新
          </el-button>
          
          <el-button
            type="success"
            :icon="Download"
            size="small"
            @click="exportLogs"
            :loading="isExporting"
          >
            导出
          </el-button>
          
          <el-button
            type="warning"
            :icon="Delete"
            size="small"
            @click="clearLogs"
            :loading="isClearing"
          >
            清空
          </el-button>
          
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            size="small"
            @change="toggleAutoRefresh"
          />
        </div>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <div class="stats-container">
      <div class="stat-item">
        <div class="stat-value">{{ totalLogs }}</div>
        <div class="stat-label">总数</div>
      </div>
      <div class="stat-item error">
        <div class="stat-value">{{ errorCount }}</div>
        <div class="stat-label">错误</div>
      </div>
      <div class="stat-item warning">
        <div class="stat-value">{{ warnCount }}</div>
        <div class="stat-label">警告</div>
      </div>
      <div class="stat-item info">
        <div class="stat-value">{{ infoCount }}</div>
        <div class="stat-label">信息</div>
      </div>
      <div class="stat-item debug">
        <div class="stat-value">{{ debugCount }}</div>
        <div class="stat-label">调试</div>
      </div>
    </div>

    <!-- 日志列表 -->
    <el-card class="logs-card" shadow="never">

      
      <div class="logs-container" ref="logsContainer">
        <div v-if="isLoading" class="loading-container">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        
        <div v-else-if="filteredLogs.length === 0" class="empty-container">
          <el-empty description="暂无日志数据" :image-size="60" />
        </div>
        
        <div v-else class="logs-list">
          <div
            v-for="log in paginatedLogs"
            :key="log.id"
            :class="['log-item', `log-${log.level}`]"
          >
            <el-collapse>
              <el-collapse-item name="log-details">
                <template #title>
                  <div class="log-summary">
                    <div class="log-meta">
                      <el-tag
                        :type="getLevelTagType(log.level)"
                        size="small"
                        class="level-tag"
                      >
                        {{ log.level }}
                      </el-tag>
                      
                      <el-tag
                        type="info"
                        size="small"
                        class="category-tag"
                      >
                        {{ getCategoryLabel(log.category) }}
                      </el-tag>
                      
                      <span class="log-time">{{ formatTime(log.timestamp) }}</span>
                    </div>
                    
                    <div class="log-message-preview">{{ log.message }}</div>
                    
                    <div class="log-actions" @click.stop>
                      <el-button
                        type="text"
                        size="small"
                        @click="copyLogContent(log)"
                      >
                        复制
                      </el-button>
                    </div>
                  </div>
                </template>
                
                <div class="log-details-content">
                  <pre>{{  log.details }}</pre>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
        
        <!-- 分页 -->
        <div v-if="filteredLogs.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[20, 50, 100]"
            :total="filteredLogs.length"
            layout="total, prev, pager, next"
            size="small"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { 
  Search, 
  Refresh, 
  Download, 
  Delete, 
  Loading 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

/**
 * 响应式数据定义
 */
const logs = ref([])
const searchKeyword = ref('')
const selectedLevel = ref('')
const selectedCategory = ref('')
const dateRange = ref([])
const autoRefresh = ref(false)
const isLoading = ref(false)
const isRefreshing = ref(false)
const isExporting = ref(false)
const isClearing = ref(false)
const currentPage = ref(1)
const pageSize = ref(50)
const logsContainer = ref(null)

// 自动刷新定时器
let refreshTimer = null

/**
 * 计算属性
 */
const totalLogs = computed(() => logs.value.length)
const errorCount = computed(() => logs.value.filter(log => log.level === 'ERROR').length)
const warnCount = computed(() => logs.value.filter(log => log.level === 'WARN').length)
const infoCount = computed(() => logs.value.filter(log => log.level === 'INFO').length)
const debugCount = computed(() => logs.value.filter(log => log.level === 'DEBUG').length)

// 过滤后的日志
const filteredLogs = computed(() => {
  let filtered = logs.value

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(log => 
      log.message.toLowerCase().includes(keyword) ||
      (log.details && log.details.toLowerCase().includes(keyword))
    )
  }

  // 按级别过滤
  if (selectedLevel.value) {
    filtered = filtered.filter(log => log.level === selectedLevel.value)
  }

  // 按分类过滤
  if (selectedCategory.value) {
    filtered = filtered.filter(log => log.category === selectedCategory.value)
  }

  // 按时间范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [startTime, endTime] = dateRange.value
    filtered = filtered.filter(log => {
      const logTime = new Date(log.timestamp).getTime()
      return logTime >= new Date(startTime).getTime() && 
             logTime <= new Date(endTime).getTime()
    })
  }

  // 按时间倒序排列
  const result = filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
  return result
})

// 分页后的日志
const paginatedLogs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredLogs.value.slice(start, end)
})

/**
 * 获取日志级别对应的标签类型
 * @param {string} level - 日志级别
 * @returns {string} 标签类型
 */
const getLevelTagType = (level) => {
  const typeMap = {
    'ERROR': 'danger',
    'WARN': 'warning',
    'INFO': 'primary',
    'DEBUG': 'info'
  }
  return typeMap[level?.toUpperCase()] || 'info'
}

/**
 * 获取分类标签文本
 * @param {string} category - 分类值
 * @returns {string} 分类标签
 */
const getCategoryLabel = (category) => {
  const labelMap = {
    'system': '系统',
    'audio': '音频处理',
    'user': '用户操作',
    'network': '网络',
    'file': '文件操作'
  }
  return labelMap[category] || category
}

/**
 * 格式化时间显示
 * @param {string} timestamp - 时间戳
 * @returns {string} 格式化后的时间
 */
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

/**
 * 加载日志数据
 */
const loadLogs = async () => {
  try {
    isLoading.value = true
    // 调用 IPC 获取日志数据
    const response = await window.electronAPI?.getLogs?.() || { success: false, logs: [] }
    
    if (response.success) {
      logs.value = response.logs || []
    } else {
      console.error('获取日志失败:', response.message)
      ElMessage.error(response.message || '获取日志失败')
      logs.value = []
    }
  } catch (error) {
    console.error('加载日志失败:', error)
    ElMessage.error('加载日志失败')
    logs.value = []
  } finally {
    isLoading.value = false
  }
}

/**
 * 刷新日志
 */
const refreshLogs = async () => {
  try {
    isRefreshing.value = true
    await loadLogs()
    ElMessage.success('日志刷新成功')
  } catch (error) {
    ElMessage.error('刷新日志失败')
  } finally {
    isRefreshing.value = false
  }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  currentPage.value = 1
}

/**
 * 处理过滤
 */
const handleFilter = () => {
  currentPage.value = 1
}

/**
 * 导出日志
 */
const exportLogs = async () => {
  try {
    isExporting.value = true
    
    // 准备导出数据
    const exportData = filteredLogs.value.map(log => ({
      时间: formatTime(log.timestamp),
      级别: log.level.toUpperCase(),
      分类: getCategoryLabel(log.category),
      消息: log.message,
      详情: log.details || ''
    }))
    
    // 调用 IPC 导出日志
    const result = await window.electronAPI?.exportLogs?.(exportData)
    
    if (result?.success) {
      ElMessage.success(`日志导出成功: ${result.filePath}`)
    } else {
      throw new Error(result?.error || '导出失败')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  } finally {
    isExporting.value = false
  }
}

/**
 * 清空日志
 */
const clearLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    isClearing.value = true
    
    // 调用 IPC 清空日志
    const result = await window.electronAPI?.clearLogs?.()
    
    if (result?.success) {
      logs.value = []
      ElMessage.success('日志清空成功')
    } else {
      throw new Error(result?.error || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空日志失败:', error)
      ElMessage.error('清空日志失败')
    }
  } finally {
    isClearing.value = false
  }
}

/**
 * 复制日志内容
 * @param {Object} log - 日志对象
 */
const copyLogContent = async (log) => {
  try {
    const content = `[${formatTime(log.timestamp)}] [${log.level.toUpperCase()}] [${getCategoryLabel(log.category)}] ${log.message}${log.details ? '\n详情: ' + log.details : ''}`
    
    await navigator.clipboard.writeText(content)
    ElMessage.success('日志内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

/**
 * 切换自动刷新
 * @param {boolean} enabled - 是否启用自动刷新
 */
const toggleAutoRefresh = (enabled) => {
  if (enabled) {
    refreshTimer = setInterval(() => {
      loadLogs()
    }, 5000) // 每5秒刷新一次
    ElMessage.info('已启用自动刷新（每5秒）')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
}

/**
 * 处理分页大小变化
 * @param {number} size - 新的分页大小
 */
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

/**
 * 处理当前页变化
 * @param {number} page - 新的当前页
 */
const handleCurrentChange = (page) => {
  currentPage.value = page
  
  // 滚动到顶部
  nextTick(() => {
    if (logsContainer.value) {
      logsContainer.value.scrollTop = 0
    }
  })
}

/**
 * 组件挂载时的初始化
 */
onMounted(() => {
  loadLogs()
})

/**
 * 组件卸载时的清理
 */
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped lang="scss">
.log-manager-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

// 工具栏样式
.toolbar-card {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
  
  .search-filters {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
    flex: 1;
    
    .search-input {
      width: 200px;
    }
    
    .level-select,
    .category-select {
      width: 100px;
    }
    
    .date-picker {
      width: 300px;
    }
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }
}

// 统计信息样式
.stats-container {
  display: flex;
  gap: 12px;

  
  .stat-item {
    flex: 1;
    padding: 8px 12px; /* 减少垂直内边距 */
    background: var(--el-bg-color);
    border: 1px solid var(--el-border-color-light);
    border-radius: 6px;
    text-align: center;
    display: flex; /* 使用 flex 布局 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    gap: 8px; /* 数值和标签之间的间距 */
    
    .stat-value {
      font-size: 18px; /* 稍微减小字体 */
      font-weight: bold;
      color: var(--el-color-primary);
      margin-bottom: 0; /* 移除底部外边距 */
    }
    
    .stat-label {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
    
    &.error .stat-value {
      color: var(--el-color-danger);
    }
    
    &.warning .stat-value {
      color: var(--el-color-warning);
    }
    
    &.info .stat-value {
      color: var(--el-color-info);
    }
    
    &.debug .stat-value {
      color: var(--el-color-success);
    }
  }
}

// 日志列表样式
.logs-card {
  flex: 1;
  display: flex;
  flex-direction: column;

  :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    height: 0%;
  }
  
  .logs-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .logs-count {
      font-size: 11px;
      color: #909399;
    }
  }
  
  .logs-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 12px;
    height: 70%;
  }
  
  .loading-container,
  .empty-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    
    .el-icon {
      font-size: 20px;
      margin-bottom: 6px;
    }
  }
  
  .logs-list {
    flex: 1;
    overflow-y: auto;
    height: 70%;

    
    .log-item {
      border: 1px solid #ebeef5;
      border-radius: 6px;
      margin-bottom: 8px;
      background: #fff;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.1);
      }
      
      &.log-error {
        border-left: 3px solid #f56c6c;
      }
      
      &.log-warn {
        border-left: 3px solid #e6a23c;
      }
      
      &.log-info {
        border-left: 3px solid #409eff;
      }
      
      &.log-debug {
        border-left: 3px solid #909399;
      }
      
      :deep(.el-collapse) {
        border: none;
        
        .el-collapse-item {
          border-bottom: none;
          
          .el-collapse-item__header {
            background: transparent;
            border: none;
            padding: 0px 12px;
            height: auto;
            line-height: normal;
            
            .log-summary {
              display: flex;
              align-items: center;
              width: 100%;
              gap: 12px;
              
              .log-meta {
                display: flex;
                align-items: center;
                gap: 6px;
                flex-shrink: 0;
                
                .level-tag,
                .category-tag {
                  font-size: 10px;
                }
                
                .log-time {
                  font-size: 11px;
                  color: #909399;
                }
              }
              
              .log-message-preview {
                flex: 1;
                font-size: 12px;
                color: #303133;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                margin: 0 12px;
                box-sizing: border-box;
              }
              .log-message-preview{
                color: #dddddd;
              }
              .log-actions {
                flex-shrink: 0;
                
                .el-button {
                  padding: 2px 6px;
                }
              }
            }
          }
          
          .el-collapse-item__content {
            padding: 0 12px 12px 12px;
            
            .log-details-content {
              strong {
                display: block;
                margin-bottom: 4px;
                font-size: 12px;
                color: var(--el-text-color-regular); /* 适配暗黑模式 */
              }
              
              pre {
                background: var(--el-fill-color-light); /* 适配暗黑模式 */
                border: 1px solid var(--el-border-color-lighter); /* 适配暗黑模式 */
                border-radius: 4px;
                padding: 8px;
                font-size: 11px;
                line-height: 1.4;
                overflow-x: auto;
                white-space: pre-wrap;
                word-break: break-word;
                margin: 0;
                color: var(--el-text-color-primary); /* 适配暗黑模式 */
              }
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    padding: 12px 0;
    border-top: 1px solid rgb(76, 76, 77);
    display: flex;
    justify-content: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .log-manager-container {
    gap: 8px;
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch !important;
    
    .search-filters {
      justify-content: center;
      
      .search-input,
      .level-select,
      .category-select,
      .date-picker {
        width: 100%;
        max-width: 180px;
      }
    }
    
    .action-buttons {
      justify-content: center;
    }
  }
  
  .stats-container {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .log-header {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 6px;
  }
}

// 暗色主题适配
.dark {
  .log-manager-container {
    background: var(--el-bg-color-page);
    
    .stats-container {
      .stat-item {
        background: var(--el-bg-color);
        border-color: var(--el-border-color);
      }
    }
    
    .logs-list {
      .log-item {
        background: var(--el-bg-color);
        border-color: var(--el-border-color);
        
        &:hover {
          border-color: var(--el-color-primary);
          box-shadow: 0 1px 4px rgba(255, 255, 255, 0.1);
        }
        
        .log-header {
          background: var(--el-fill-color-light);
          border-bottom-color: var(--el-border-color);
        }
        
        .log-details {
          :deep(.el-collapse) {
            .el-collapse-item__header {
              background: var(--el-fill-color-dark);
              border-color: var(--el-border-color);
            }
            
            .el-collapse-item__content {
              pre {
                background: var(--el-fill-color-dark);
                border-color: var(--el-border-color);
              }
            }
          }
        }
      }
    }
  }
}
</style>